Getting Started with Custom JavaScript in Forms
Note: This section applies to classic forms. For CSS and Javascript in the Form Designer, see this section.
This section introduces you to the basic syntax of JavaScript. To get the most out of it, you should already know what an HTML element is.
Unlike CSS selectors, JavaScript selectors can target not just an element, but also the values of elements like input boxes, checkboxes, and radio buttons. Using JavaScript selectors on the values of elements, you can add, modify, or delete elements of the form depending on the values that users enter in other elements. JavaScript selectors can also detect events such as fields being changed or buttons being clicked. By writing functions that trigger upon these events, you can make your form dynamically respond to users' actions.
Syntax
Like CSS selectors, JavaScript selectors target HTML elements. As such, you should use the same methods as those described in Customizing a Form with CSS and Javascript and CSS Selectors to find the elements and attributes of interest.
Javascript in the Classic Designer
The Classic Designer uses the popular JavaScript library jQuery. In jQuery, a selector starts with a $
sign, followed by parentheses and quotes (single or double) that contain the id selected. For example, to target the first field in a form, use the selector $('#q1')
. You can also target ids that meet certain criteria, such as being selected (for checkboxes) or starting with a certain string. As with CSS selectors, ids are preceded by a #
, while classes are preceded by a period.
To target elements based on attributes other than ids and classes, use the format [attribute="value"]
. For example, to select all elements that have the type text, use $('[type="text"]')
.
Compound Selectors
Sometimes you may need to combine multiple selectors to target the element(s) you desire. Compound selectors let you do so in a variety of different ways.
To select elements that satisfy any of a list of conditions: Use a comma to separate each component selector. Your intended targets only have to satisfy at least one of the selectors in the comma-separated list. E.g. $("div, span").css("border", "3px solid red")
gives all div elements and all span elements a border that is 3 pixels wide and red.
To select elements that satisfy all conditions in a list of conditions: Chain together the component selectors without a space. Sometimes this may necessitate using square brackets in your component selectors. For example, $('[type="text"][name="Field3"]')
selects all elements that have their type attribute set to text
and their name attribute set to Field3
. $('input.TwoPerLine')
selects all input elements that have the custom class TwoPerLine
. $('input[type="text"]')
selects all input elements that have the type text
.
To select descendants of an element: Separate the ancestor and the descendant with a space. For example, $('#q1 input')
selects all input elements within the element with id q1
.
To select the immediate children of an element: Separate the parent and child with a >
. For example, $('.cf-collection > div')
selects all div elements that are immediate children of an element with class cf-collection
. This syntax does not select any ancestors of the parent that are not its immediate children. For example, in a HTML snippet that has the structure <ul><li><input ... ></li></ul>
, a selector like ul > input
would not select the embedded input element, because the input element is not an immediate child of ul. li > input
, however, would select that input element.
Commonly used jQuery selectors in Forms
Syntax | Use | Example |
---|---|---|
$('#q1') | Targets the field with id q1. Useful as a selector for events. | $('#q1').change(function () { |
$('#q1 input') | Targets the input box of the field with id q1. To obtain the value in the input box, append .val(). | $('#q1 input').val() |
$('#Field4(2) input') | Targets an input box in a table. The ID attribute for input boxes in table rows has the format FieldFieldNumber(RowNumber). To find out what FieldNumber a column is identified by, use your browser's HTML inspection tools. The row numbers start at 1 for the first row. This particular selector targets the input box that is in the second row of a column with id Field4. | $('#Field4(2) input').val() |
$('[id^="Field4"]') | Targets field input boxes that start with Field4. Useful for targeting all input boxes in a table column. The id attribute for input boxes in table rows has the format FieldFieldNumber(RowNumber). Using this selector syntax is a way to target all input boxes in a particular column. | $('[id^=Field4]').val() |
$("[id$='(2)']") | Targets the input boxes in the second rows of tables, by selecting all elements with ids that end with (2). | $("[id$='(2)']").val() |
$("input[id^='Field14']:checked") | Targets selected radio buttons or checkboxes that have an id starting with Field14. | $('input[id^="Field14"]:checked').val() |
$('#Field6_other_value') | Targets the text in the input box for an "Other" choice in the radio button or checkbox field with id q6. | $('#Field6_other_value').val() |
$('select[id^="Field14"]') | Targets the input box of drop-down fields whose id starts with Field14. Useful if you want the selected value of a drop-down field. | $('select[id^="Field14"]').val() |
$('.cf-collection > div') | For collections with repeating sets of fields, targets the div container that wraps each set of fields. This works because the divs are immediate children of the element with class .cf-collection. | $('.cf-collection > div').each(function () { //function definition } |
.cf-table-block tbody tr | Targets the rows of a table. | See Iterating over Table Rows |
Note: For more information on jQuery selectors, see jQuery's online documentation.
jQuery Methods
Selectors pick out elements on a page; methods process features of those elements. A selector like $('#q1 input')
, taken by itself, does not pick out the value of the selected input—you need to append a method to the selector in order to obtain values. For example, $('#q4 input').val()
indicates that one is extracting the value of the input for the field with id q4
.
Name | Syntax | Use | Example |
---|---|---|---|
Value | .val() to get value; .val(newValue) to set value. | Used to get the value of an element. By passing a value into this method (by including it in the parentheses), this method can also set the value of an element. When using this method, be sure the selector is targeting elements that have values (e.g., input boxes). |
Get existing value of element: Set the selected element to have the value New Value: |
Each | .each(selector) | Used to iterate over elements within a jQuery object. Most useful when you want to carry out an operation over multiple elements that all satisfy a certain condition. For example, you can iterate over all rows in a table, or all divs in a collection. | See Customizing Tables for some examples. |
Find | .find(selector) | Searches through the descendants of the elements that match the selector and returns a new jQuery object consisting of the matching elements. |
To find all li elements that are descendants of ul elements , where the latter are themselves within the element with id q5: $('#q5').find('ul li') |
Closest | .closest(selector) | Finds the closest ancestors of the elements that match the selector. This can be useful when you want to target the container of an input box using selectors on the input box's attributes. | To find the closest div elements containing input text boxes: $('input[type="text"]').closest('div') |
Length | .length() | Returns the number of elements in the jQuery object it is applied to. Useful for counting the number of rows in a table of variable length, or the number of sets in a repeatable collection. | $('#q20 .rpx').length() returns the number of descendant elements with class rpx in the element with id q20. This effectively counts the number of repeating sets of fields in a collection. |
Replace | .replace() | Used to replace parts of a value. This method uses regular expression syntax. |
To remove all commas in the value (by replacing them with nothing): $('#Field4').val().replace(/,/,g,''); |
Functions
Functions take in an input and produce an output. For example, you may want to output a yes/no decision about whether to show a certain part of a form, based on the values that the user has entered in some fields. You can write a function to do this. The following functions are built into JavaScript and are particularly useful for converting one form of data into another.
Name | Syntax | Use | Example |
---|---|---|---|
Number | Number() | Converts a value (usually a string) to a number. This is useful if you are working with numbers that have been entered in fields that also accept characters (e.g., single line fields). |
Converts the value of the field to a number, removing commas. |
ParseFloat | parseFloat() | Converts a value (usually a string) to a floating point number (a number with a decimal point). This is useful if you are working with monetary values that have been entered in fields that also accept characters (e.g., Single line). |
Converts the value of the field to a floating point number. |
Events
Unlike CSS, JavaScript allows the web page to respond to events on the page. You can specify changes to happen based on what is clicked, focused on, changed, loaded, and so on. For example, changes that should happen once the page loads are typically encapsulated in a $(document).ready
function. Most of the examples we provide in these pages are enclosed in such a function, as we typically do not need customizations that take place before a page fully loads.
Events must be attached to an element using a selector. This specifies which part of the page has to be loaded, clicked on, and so on to trigger the processes specified in the function. If you find that your JavaScript is not running, it may be that the event it is attached to has not happened, or that it is not attached to an event.
Name | Syntax | Use | Example |
---|---|---|---|
Ready | $('selector').ready( function () { | Tells the browser to run the code inside the function when the element specified in the selector has loaded. |
Run the enclosed code when the page has loaded: $(document).ready(function () { //code goes here }) |
Click | $('selector').click( function () { | Tells the browser to run the code inside the function when the element is clicked. For example, you may want to display certain text when the user clicks a button. |
Run the enclosed code when an input element within the element with id q4 is clicked: $('#q4 input').click(function () { |
Blur | $('selector').blur( function () { | Tells the browser to run the code inside the function when the element loses focus (i.e., when the user clicks out of the element). For example, you may want to display a warning message if the user enters an invalid value and tries to move on to another field. |
Run the enclosed code when the user clicks out of an input element within the element with id q4: $('#q4 input').blur(function () { |
Focus | $('selector').focus( function () { | Tells the browser to run the code inside the function when the element gains focus (i.e., when the user mouses over the element). For example, you may want to display certain hints when the user hovers over an input box. |
Run the enclosed code when an input element within the element with id q4 is focused on: $('#q4 input').focus(function () { |
Change | $('selector').change( function () { | Tells the browser to run the code inside the function when the element changes. This event is useful if you want to run a function when the value of a field changes. For example, you may want the value of another field to be recalculated when the user changes the value of one of the inputs that is used in the calculation. |
Run the enclosed code when the value of an input element within the element with id q4 is changed: $('#q4 input').val().change(function () { |